<!-- PaperAdd 试卷添加 -->
<template>
  <div class="content">
    <el-form class="page-form" :model="data" :rules="rules" ref="paperForm" size="medium" label-width="100px">
      <el-form-item label="试卷标题：" prop="title">
        <el-input class="page-form-item" v-model="data.title" placeholder="请输入试卷标题（不得超过30字）" maxlength="30"></el-input>
      </el-form-item>
      <el-form-item label="试卷类型：" prop="paperType">
        <Cselect v-model="data.paperType" @change="handlePaperTypeChange" :clearable="false" :options="paperTypeList"
          placeholder="请选择试卷类型"></Cselect>
      </el-form-item>

      <template v-if="data.paperType === '1'">
        <el-form-item label="题目：" prop="topicIds">
          <el-input class="hidden-input" v-model="data.topicIds" placeholder=""></el-input>
          <div v-if="selectTopics.length <= 0" style="color:rgb(96, 98, 102);">未选择题目</div>
          <div v-else class="topics" style="color:rgb(96, 98, 102);">
            <div v-for="(item, index) in selectTopics" :key="item.id">
              <div class="topic-title" style="color:rgb(0, 0, 0);">{{index + 1 + "、"}}{{item.title}}</div>
              <div>
                <span>类型：{{dealStr(item.type, 'typeList')}}</span>
                <span style="margin:0 50px;">分值：{{item.maxScore}}</span>
                <span class="topic-answer">正确答案{{returnAnswer(item)}}</span>
              </div>
              <div>
                <!-- 排序&nbsp; <el-input @input="onSortChange($event, item, index)" :value="item.sort" style="width: 70px;" size="small"></el-input>&nbsp; -->
                <el-button size="mini" type="danger" @click="onRemoveTopics(item, index)">删除</el-button>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="onAddTopic">添加试题</el-button>
        </el-form-item>
      </template>
      <template v-if="data.paperType === '2'">
        <el-form-item label="随机规则：" prop="paperType">
          <div class="paper-rule">
            <div class="t-table">
              <div class="t-head">
                <span>序号</span>
                <span>题目类型</span>
                <span>难度</span>
                <span>所属课程</span>
                <span>题数</span>
                <span>分值</span>
                <span>操作</span>
              </div>
              <div class="t-body">
                <div class="t-th" v-for="(item, index) in paperRule" :key="index">
                  <span>{{index + 1}}</span>
                  <span>{{item.typeStr}}</span>
                  <span>{{item.difficultStr}}</span>
                  <span>{{item.courseName || ''}}</span>
                  <span>{{item.num || ''}}</span>
                  <span>{{item.score || 0}}</span>
                  <span class="click-ele danger" style="margin: 0; color: #f56c6c;" @click="handleOprRule(2, index)">删除</span>
                </div>
                <div style="color: #63656a; text-align: center;" v-if="!paperRule || paperRule.length <= 0 ">暂无规则</div>
              </div>
            </div>
            <div class="add-rule click-ele" style="margin: 0;" @click="handleOprRule(1)">创建规则</div>
          </div>

        </el-form-item>
      </template>

      <el-form-item label="试卷分值：" prop="maxScore"> {{data.maxScore}} </el-form-item>
      <el-form-item label="题数：" prop="topicCount"> {{data.topicCount}} </el-form-item>

      <el-form-item>
        <el-button @click="handleResetForm('paperForm')">返 回</el-button>
        <el-button type="primary" :loading="btnLoading" @click="handleSubmitForm('paperForm')">保 存</el-button>
      </el-form-item>
    </el-form>

    <!-- 选题目 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.mVisible" class="dialog-form" width="800px">
      <el-form :model="query" ref="searchForm" label-width="100px" size="mini">
        <el-row>
          <el-col :span="12">
            <span style="padding-left: 20px;margin-right:100px;">已选题目：{{dialog.topicCount}}</span>
            <span>分值：{{dialog.maxScore}}</span>
          </el-col>
          <el-col :span="12">
            <el-form-item label="试题类型：" prop="type">
              <el-select v-model="query.type" placeholder="请选择试题类型" clearable @change="onQueryChange">
                <el-option label="全部" value=""></el-option>
                <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="试题难度：" prop="title">
              <el-select v-model="query.difficult" placeholder="请选择试题难度" clearable @change="onQueryChange">
                <el-option label="全部" value=""></el-option>
                <el-option v-for="item in difficultList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属课程：" prop="courseId">
              <el-select v-model="query.courseId" placeholder="请选择所属课程" clearable @change="onQueryChange">
                <el-option label="全部" value=""></el-option>
                <el-option v-for="item in coruseList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table :data="dialog.tableList" v-loading="dialog.tableLoading" ref="dialogTableData" border fit
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="title" label="题目" align="center" min-width="200"></el-table-column>
        <el-table-column prop="title" label="所属课程" align="center" min-width="200">
          <template slot-scope="scope">
            {{dealStr(scope.row.courseId, 'coruseList')}}
          </template>
        </el-table-column>
        <el-table-column prop="title" label="题目类型" align="center">
          <template slot-scope="scope">
            {{dealStr(scope.row.type, 'typeList')}}
          </template>
        </el-table-column>
        <el-table-column prop="rightAnswer" label="正确答案" align="center"></el-table-column>
        <el-table-column prop="maxScore" label="分值" align="center"></el-table-column>
      </el-table>

      <Pagination @pageChange="getPage" :pageDefultData="{
        pageNum: query.pageNum,
        pageRow: query.pageSize,
        totalCount: dialog.totalCount }">
      </Pagination>

      <span slot="footer" class="dialog-footer" style="text-align: center;display: block;">
        <el-button size="medium" @click="dialog.mVisible = false">取 消</el-button>
        <el-button size="medium" type="primary" @click="handleDiaSub('DlalogForm')">确
          定</el-button>
      </span>

    </el-dialog>
    <!-- 选题目 -->

    <el-dialog :title="ruleDialog.title" :visible.sync="ruleDialog.show" :width="ruleDialog.width">
      <el-form :model="ruleDialog.data" :rules="ruleDialog.rules" ref="ruleForm" label-width="100px" size="medium">
        <el-form-item label="试题类型：" prop="type">
          <Cselect v-model="ruleDialog.data.type" :options="typeList" @change="($event) => handleRuleChange($event, 1)"
            :clearable="false" placeholder="请选择试题类型"></Cselect>
        </el-form-item>
        <el-form-item label="试题难度：" prop="difficult">
          <Cselect v-model="ruleDialog.data.difficult" :options="difficultList" @change="($event) => handleRuleChange($event, 2)"
            :clearable="false" placeholder="请选择试题难度"></Cselect>
        </el-form-item>
        <el-form-item label="所属课程：" prop="courseId">
          <Cselect v-model="ruleDialog.data.courseId" :options="coruseList" @change="($event) => handleRuleChange($event, 3)"
            :clearable="false" placeholder="请选择所属课程"></Cselect>
        </el-form-item>
        <el-form-item label="随机抽取：" prop="num">
          <el-input v-model="ruleDialog.data.num" placeholder="请输入抽取题量"></el-input>
        </el-form-item>
        <el-form-item label="每题分值：" prop="score">
          <el-input v-model="ruleDialog.data.score" placeholder="请输入每题分值"></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align: center;">
        <el-button size="medium" @click="handleCancle('ruleForm')">取 消</el-button>
        <el-button size="medium" type="primary" :loading="ruleDialog.ruleSubLoading" @click="handleDiaRuleSub('ruleForm')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { GetQuestionListWithoutPage, GetCourseListWithoutPage, AddPaper } from '@/api/train'
import { PaperFormRules, PaperRuleRules } from '@/utils/rules'
import { ExportList } from '@/utils'
export default {
  name: 'PaperAdd',
  components: {},
  data () {
    return {
      data: {
        title: '',
        paperType: '1',
        maxScore: 0,
        topicCount: 0,
        topicIds: ''
      },
      // 选择的题目
      selectTopics: [],
      btnLoading: false,
      rules: PaperFormRules,
      coruseList: [],
      paperTypeList: ExportList('paperTypeList'),
      typeList: ExportList('questionTypeList'),
      difficultList: ExportList('difficultList'),
      dialog: {
        mVisible: false,
        title: '选择试题',
        tableList: [],
        totalCount: 0,
        tableLoading: false,
        maxScore: 0,
        topicCount: 0,
        selectTopics: []
      },
      paperRule: [],
      ruleDialog: {
        show: false,
        ruleSubLoading: false,
        title: '创建规则',
        width: '600px',
        data: {
          typeStr: '',
          type: '',
          difficultStr: '',
          difficult: '',
          courseName: '',
          courseId: '',
          num: '',
          score: ''
        },
        rules: PaperRuleRules
      },
      query: {
        pageNum: 1,
        pageSize: 10
      }
    }
  },
  props: {},
  watch: {},
  computed: {},
  mounted () {
    this.getCoruse()
  },
  methods: {
    handlePaperTypeChange (val) {
      this.data.maxScore = '0'
      this.data.topicCount = '0'
      if (val === '2') {
        this.selectTopics = []
      }
      if (val === '1') {
        this.paperRule = []
      }
    },
    // 打开弹窗
    onAddTopic () {
      this.getQuestions()
      this.dialog.mVisible = true
    },
    // 表单提交
    handleSubmitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) return
        let params = {
          title: this.data.title
        }
        if (this.data.paperType === '1') { // 固定试题
          params.type = '1'
          params.topicIds = []
          if (this.selectTopics.length <= 0) {
            this.$message.warning('请选择试题')
            return
          }
          this.selectTopics.forEach(item => {
            const info = { id: item.id, sort: item.sort || 0 }
            params.topicIds.push(info)
          })
        }
        if (this.data.paperType === '2') { // 随机试题
          params.type = '2'
          params.courseRelation = []
          if (this.paperRule.length <= 0) {
            this.$message.warning('请添加试卷规则！')
            return
          }
          this.paperRule.forEach((e, index) => {
            const item = {
              courseId: e.courseId,
              sort: index + 1,
              topicCount: e.num || '0',
              topicDifficult: e.difficult || '',
              topicScore: e.score || '0',
              topicType: e.type || ''
            }
            params.courseRelation.push(item)
          })
        }
        this.doAddPaper(params)
      })
    },
    // 表单返回
    handleResetForm (formName) {
      this.$router.go(-1)
    },

    // 弹窗提交
    handleDiaSub () {
      if (this.dialog.selectTopics.length <= 0) {
        this.$message.warning('请选择试题')
        return
      }
      // 设置值
      this.data.topicIds = '1'
      const selectTopicsIds = this.selectTopics.map(item => item.id)
      this.dialog.selectTopics.forEach(item => {
        if (selectTopicsIds.indexOf(item.id) === -1) {
          this.selectTopics.push(item)
        }
      })
      this.selectTopics.forEach((item, index) => {
        item.sort = index + 1
      })
      this.countmaxScore()
      this.dialog.mVisible = false
    },
    // 排序改变
    onSortChange (event, item, index) {
      item.sort = event
      this.selectTopics.splice(index, 1, item)
    },
    // 移除某试题
    onRemoveTopics (item, index) {
      // if (this.selectTopics.length <= 1) {
      //   this.$message.warning('最后一项试题不可删除')
      //   return
      // }
      this.selectTopics.splice(index, 1)
      this.selectTopics.forEach((item, index) => {
        item.sort = index + 1
      })
      this.countmaxScore()
    },
    // 计算分支 题量
    countmaxScore (type) {
      let totalScore = 0
      let topicCount = 0
      if (type === 2) {
        this.paperRule.forEach(e => {
          const num = parseInt(e.num)
          const score = parseInt(e.score)
          totalScore += num * score
          topicCount += num
        })
      } else {
        this.selectTopics.forEach((item, index) => {
          item.sort = index + 1
          totalScore += item.maxScore
        })
        topicCount = this.selectTopics.length
      }
      this.data.maxScore = totalScore
      this.data.topicCount = topicCount
    },
    // 表单正确答案显示
    returnAnswer (val) {
      let answerStr = ''
      if (val.type === '3' || val.type === 3) {
        answerStr = val.rightAnswer
      } else {
        const rightAnswers = val.rightAnswer.split(',')
        rightAnswers.forEach(item => {
          const key = 'select' + item
          answerStr += item + '、' + val[key] + '   '
        })
      }
      return answerStr
    },
    // 弹窗查询
    onQueryChange () {
      this.query.pageNum = 1
      this.getQuestions()
    },
    // 分页处理
    getPage (val) {
      this.query.pageNum = val.pageNum
      this.query.pageSize = val.pageRow
      this.getQuestions()
    },
    // 表格勾选处理
    handleSelectionChange (selection) {
      this.dialog.topicCount = selection.length
      this.dialog.selectTopics = selection
      this.dialog.maxScore = 0
      selection.forEach(e => {
        this.dialog.maxScore = this.dialog.maxScore + e.maxScore
      })
    },
    // 表格数据对应处理
    dealStr (key, listKey) {
      const arr = this[listKey]
      let str = ''
      arr.forEach(e => {
        const valueNumber = parseInt(e.value)
        if (e.value === key || valueNumber === key) {
          str = e.label
        }
      })
      return str
    },
    // 试题表格数据获取
    getQuestions () {
      let params = JSON.parse(JSON.stringify(this.query))
      this.dialog.tableLoading = true
      GetQuestionListWithoutPage(params).then(res => {
        this.dialog.tableLoading = false
        const data = res.data
        this.dialog.tableList = data.list
        this.dialog.totalCount = data.total
      }).catch(e => {
        this.dialog.tableLoading = false
      })
    },
    // 弹窗课程数据获取
    getCoruse () {
      GetCourseListWithoutPage().then(res => {
        const data = res.data
        data.list.forEach(e => {
          e.value = e.id.toString()
          e.label = e.title
        })
        this.coruseList = data.list
      }).catch(e => {
        this.coruseList = []
      })
    },
    /* 添加试卷-api */
    doAddPaper (params) {
      this.btnLoading = true
      AddPaper(params).then(res => {
        this.$message.success(res.message || '修改成功')
        setTimeout(() => {
          this.btnLoading = false
          this.$router.go(-1)
        }, 500)
      }).catch(e => {
        this.btnLoading = false
      })
    },
    handleOprRule (type, index) {
      if (type === 1) { // add
        this.ruleDialog.show = true
      } else {
        this.paperRule.splice(index, 1)
        this.countmaxScore(2)
      }
    },
    handleRuleChange (val, type) {
      if (type === 1) {
        this.ruleDialog.data.typeStr = this.typeList.filter(e => e.value === val)[0].label
      }
      if (type === 2) {
        this.ruleDialog.data.difficultStr = this.difficultList.filter(e => e.value === val)[0].label
      }
      if (type === 3) {
        this.ruleDialog.data.courseName = this.coruseList.filter(e => e.value === val)[0].label
      }
    },
    handleCancle (formName) {
      this.ruleDialog.show = false
      this.$refs[formName].resetFields()
    },
    handleDiaRuleSub (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) return
        const ruleData = JSON.parse(JSON.stringify(this.ruleDialog.data))
        const ctd = `${ruleData.courseId}_${ruleData.type}_${ruleData.difficult}`

        // 判断已选择的课程是否有相同类型难度的试题
        const ctdList = this.paperRule.map(item => item.c_t_d)
        if (ctdList.indexOf(ctd) > -1) {
          this.$message.warning('选择了同课程下题目类型和难易程度一样的试题！')
          return
        }
        // 判断课程下是否有选中的的题目类型 难度的题量
        const params = {
          type: ruleData.type,
          courseId: ruleData.courseId,
          difficult: ruleData.difficult
        }
        this.ruleDialog.ruleSubLoading = true

        GetQuestionListWithoutPage(params).then(res => {
          this.ruleDialog.ruleSubLoading = false
          const num = res.data.total || 0
          if (parseInt(ruleData.num) <= num) {
            let ruleInfo = {
              typeStr: '',
              type: '',
              courseName: '',
              courseId: '',
              difficult: '',
              difficultStr: '',
              num: '',
              score: '',
              c_t_d: ctd // courseId + type + difficult
            }
            for (const key in ruleInfo) {
              if (ruleInfo.hasOwnProperty(key)) {
                ruleInfo[key] = ruleData[key]
              }
            }
            this.paperRule.push(ruleInfo)
            // 计算分值 题量
            this.countmaxScore(2)
            this.handleCancle(formName)
          } else {
            this.$message.error('该课程下没有相应的试题数量！')
          }
        }).catch(e => {
          if (e) {
            this.$message.error(e.message || '请求失败！')
          }
          this.ruleDialog.ruleSubLoading = false
        })
        // let ruleInfo = {
        //   typeStr: '',
        //   type: '',
        //   courseName: '',
        //   courseId: '',
        //   difficult: '',
        //   difficultStr: '',
        //   num: '',
        //   score: ''
        // }
        // for (const key in ruleInfo) {
        //   if (ruleInfo.hasOwnProperty(key)) {
        //     ruleInfo[key] = this.ruleDialog.data[key]
        //   }
        // }
        // this.paperRule.push(ruleInfo)
        // // 计算分值 题量
        // this.countmaxScore(2)
        // this.handleCancle(formName)
      })
    }
  }

}

</script>
<style lang='scss' scoped>
$borderColor: #dcdfe6;
.paper-rule {
  .t-table {
    border: 1px solid $borderColor;
    box-sizing: border-box;
    border-radius: 2px;
    span {
      display: flex;
      justify-content: center;
      align-items: center;
      flex: 7 7;
      overflow: hidden;
      text-align: center;
      line-height: 20px;
      padding: 5px 3px;
      border-right: 1px solid $borderColor;
      border-bottom: 1px solid $borderColor;
      box-sizing: border-box;
      &:nth-child(1) {
        flex: 1 1 50px;
      }
      &:nth-child(4) {
        flex: 3 1 150px;
      }
      &:nth-last-child(1) {
        border-right: none;
      }
    }
  }
  .t-head {
    display: flex;
    justify-content: flex-start;
    align-content: stretch;
    span {
      font-weight: 500;
      padding: 8px 3px;
    }
  }
  .t-th {
    display: flex;
    justify-content: flex-start;
    align-content: stretch;
    span {
      color: rgb(96, 98, 102);
    }
  }
  .t-body .t-th:nth-last-child(1) {
    span {
      border-bottom: none;
    }
  }
}
</style>
